﻿using System.IO;
using System.Web;


namespace DBFile.Core.Web
{
	/// <summary>
	/// This class is the concrete implementation of BaseHttpModule.  This implementation is designed to return
	/// a file to the Response object by determining if the asked for object exists on the file system.  If the 
	/// file does exist, then that object is returned.  If it does not exist, then the FileUtility is used to 
	/// see if it exist in the database and returned if it does.
	/// </summary>
	public class DBFileHttpModule : BaseHttpModule
	{

		#region BaseHttpModule Members
		/// <summary>
		/// Opens a file, either from the file system (if it exists) or from the database. 
		/// </summary>
		/// <param name="requestedPath">URL typed in the browser</param>
		/// <param name="app">Current HttpApplication</param>
		protected override void Open(string requestedPath, HttpApplication app)
		{
			string filepath = app.Context.Request.FilePath;
			string filename = filepath.Substring(filepath.LastIndexOf("/") + 1);

			// if the file has a physical location, load it otherwise get from database
			if (File.Exists(app.Context.Server.MapPath(filename)))
			{
				app.Context.RewritePath(filepath, string.Empty, string.Empty);
			}
			else
			{
                // TODO: Move to cache of FileNames
                //if (DBFile.Exists(filename))
                //{
                    // get the file from the database and write it to the reponse object
                    DBFile.Open(filename, app.Context.Response, false);
                
				    // if we are writing a file out of the database, end the response after because
				    // that file in the database is all the response we need.
				    app.Context.Response.End();
                //}
			}

		}
		#endregion

	}
}
